package com.wpg.demo.spring.xml.addressbook.repository.impl;

import com.wpg.demo.spring.xml.addressbook.domain.AddressBook;
import com.wpg.demo.spring.xml.addressbook.domain.PhoneNumber;
import com.wpg.demo.spring.xml.addressbook.repository.AddressBookRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ChangWei Li
 * @version 2017-02-20 09:55
 */
@Repository
public class AddressBookRepositoryImpl implements AddressBookRepository {

    private final ApplicationContext applicationContext;

    private static List<AddressBook> bookList = new ArrayList<>();

    public AddressBookRepositoryImpl(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {
        System.out.println("AddressBookRepositoryImpl After Init");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("AddressBookRepositoryImpl Before Destroy");
    }

    @Override
    public int add(AddressBook addressBook) {
        return 1;
    }

    @Override
    public List<AddressBook> getList() {
        if (bookList.isEmpty()) {
            for (int i = 0; i < 100; i++) {
                bookList.add(
                        new AddressBook(i, "name" + i, "116352590" + i + "@qq.com",
                                new PhoneNumber("0371-376821" + i, PhoneNumber.PhoneType.HOME)));
            }
        }

        System.out.println(applicationContext);

        return Collections.unmodifiableList(bookList);
    }
}
